package utils

import (
	"io"
	"os"
	"time"

	"gitee.com/xungen/goweb/errno"
)

func IsFile(filename string) bool {
	file, err := os.Stat(filename)
	if err != nil {
		return false
	}
	if file.IsDir() {
		return false
	}
	return true
}

func WriteAll(file io.Writer, buffer []byte, timeout time.Duration) (int, error) {
	var ofs int
	var sum = len(buffer)
	var end = time.Now().UnixMilli() + int64(timeout/time.Millisecond)
	for ofs < sum && end > time.Now().UnixMilli() {
		num, err := file.Write(buffer[ofs:])
		if err != nil {
			return ofs, err
		}
		ofs += num
	}
	if ofs < sum {
		return ofs, errno.TIMEOUT
	}
	return ofs, nil
}

func ReadAll(file io.Reader, buffer []byte, timeout time.Duration) (int, error) {
	var ofs int
	var sum = len(buffer)
	var end = time.Now().UnixMilli() + int64(timeout/time.Millisecond)
	for ofs < sum && end > time.Now().UnixMilli() {
		num, err := file.Read(buffer[ofs:sum])
		if io.EOF == err {
			return ofs + num, nil
		}
		if err != nil {
			return ofs, err
		}
		ofs += num
	}
	if ofs < sum {
		return ofs, errno.TIMEOUT
	}
	return ofs, nil
}
